﻿using GalaSoft.MvvmLight;
using LiveChartsCore;
using LiveChartsCore.Defaults;
using LiveChartsCore.SkiaSharpView;
using LiveChartsCore.SkiaSharpView.Painting;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Threading;
using HandyControl.Controls;
using SkiaSharp;
using System.Windows.Documents;
using LiveChartsCore.Geo;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using KINLO.UI.Main.View;
using GalaSoft.MvvmLight.Command;
using KINLO.UI.Main.Hepler;
using KINLO.Model;
using KINLO.Data.Reporitory;
using System.Collections;
using System.Windows;
using GalaSoft.MvvmLight.Messaging;
using MessageBox = System.Windows.MessageBox;
using System.IO.Ports;
using Microsoft.Win32;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;

namespace KINLO.UI.Main.VM
{
    public class PressureChartVM : ViewModelBase
    {

        public PressureChartVM() 
        {
            Init();
            //添加数据
            Messenger.Default.Register(this, "AddPressureChart", new Action<List<PressureVesselModel>>((s) => AddPressureChart(s)));

            EndTime = DateTime.Now;
            StartTime = EndTime.AddDays(-1);
            IsManualMode = true;
            IsCan1Checked = true;
            IsCan2Checked = true;
            IsCan3Checked = true;
            IsCan4Checked = true;
            //IsUpperLimitChecked=true;
            //IsLowerLimitChecked=true;

            IsFill=true;
        }
        #region 属性
        private readonly Random _random = new Random();
        private readonly ObservableCollection<ObservableValue> _observableValues;


        public ObservableCollection<ISeries> Series { get; set; }=new ObservableCollection<ISeries>();
        Axis xAxis;

        /// <summary>
        /// 上限
        /// </summary>
        private ObservableCollection<double> UpperLimit { get; set; } = new ObservableCollection<double>();
        /// <summary>
        /// 标准值
        /// </summary>
        private ObservableCollection<double> StandardValue { get; set; } = new ObservableCollection<double>(); 
        /// <summary>
        /// 下限
        /// </summary>
        private ObservableCollection<double> LowerLimit { get; set; } = new ObservableCollection<double>();

        /// <summary>
        /// 罐1
        /// </summary>
        private ObservableCollection<double> Can1 { get; set; } = new ObservableCollection<double>();
        /// <summary>
        /// 罐2
        /// </summary>
        private ObservableCollection<double> Can2 { get; set; } = new ObservableCollection<double>();
        /// <summary>
        /// 罐3
        /// </summary>
        private ObservableCollection<double> Can3 { get; set; } = new ObservableCollection<double>();
        /// <summary>
        /// 罐4
        /// </summary>
        private ObservableCollection<double> Can4 { get; set; } = new ObservableCollection<double>();



        private int _opacityFill=30;
        public int OpacityFill
        {
            get => _opacityFill;
            set
            {
                _opacityFill = value;
                if (IsFill)
                {
                    SetFillForLineSeries(IsFill);
                }
                RaisePropertyChanged(() => _opacityFill);
            }
        }

        private bool _isFill;
        /// <summary>
        /// 是否填充
        /// </summary>
        public bool IsFill
        {
            get => _isFill;
            set
            {
                _isFill = value;
                SolidColorPaint _fill;

                SetFillForLineSeries(value);

                RaisePropertyChanged(() => IsFill);
            }
        }
        
        private bool _isJump=true;
        /// <summary>
        /// 自动跳转最新数据节点
        /// </summary>
        public bool IsJump
        {
            get => _isJump;
            set
            {
                _isJump = value;
                RaisePropertyChanged(() => IsJump);
            }
        }

        private int _lineSize=3;
        /// <summary>
        /// 线条大小
        /// </summary>
        public int LineSize
        {
            get => _lineSize;
            set
            {
                _lineSize = value;
                SetLineSizeSeries(value);
                RaisePropertyChanged(() => LineSize);
            }
        }

        private int _intervalInSeconds = 180;
        /// <summary>
        ///间隔保存数据库时间，单位：秒
        /// </summary>
        public int IntervalInSeconds
        {
            get => _intervalInSeconds;
            set
            {
                if (_intervalInSeconds != value)
                {
                    if ((MessageBoxResult.OK == MessageBox.Show($"确认修改间隔保存数据库时间吗，修改：{_intervalInSeconds}=>{value}:", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Information)))
                    {
                        _intervalInSeconds = value;
                        RaisePropertyChanged(() => IntervalInSeconds);
                    }
                    else
                    {

                    }
                }
            }
        }
        private int _lineSmoothness=10;
        /// <summary>
        /// 平滑度
        /// </summary>
        public int LineSmoothness
        {
            get => _lineSmoothness;
            set
            {
              
                _lineSmoothness = value;
                SetGeometrySeries();
                RaisePropertyChanged(() => _lineSmoothness);
            }
        }

        private int _geometrySize=10;
        /// <summary>
        /// 几何尺寸
        /// </summary>
        public int GeometrySize
        {
            get => _geometrySize;
            set
            {
                _geometrySize = value;
                SetGeometrySeries();
                RaisePropertyChanged(() => _geometrySize);
              
            }
        }

        private int _sliderValueMax = 300;
        /// <summary>
        /// 显示数量最大值
        /// </summary>
        public int SliderValueMax
        {
            get => _sliderValueMax;
            set
            {
                _sliderValueMax = value;
                RaisePropertyChanged(() => SliderValueMax);
                XxisInit();
            }
        }
        private int _sliderValue = 10;
        /// <summary>
        /// 显示数量
        /// </summary>
        public int SliderValue
        {
            get => _sliderValue;
            set
            {
                _sliderValue = value;
                RaisePropertyChanged(() => SliderValue);
                XxisInit();
            }
        }
        private DateTime _startTime;
        /// <summary>
        //开始时间
        /// </summary>
        public DateTime StartTime
        {
            get => _startTime;
            set
            {
                _startTime = value;
                RaisePropertyChanged(() => StartTime);
            }
        }
        private DateTime _endTime;
        /// <summary>
        //结束时间
        /// </summary>
        public DateTime EndTime
        {
            get => _endTime;
            set
            {
                _endTime = value;
                RaisePropertyChanged(() => EndTime);
            }
        }

        private string _upperLimitTXT="650";
        /// <summary>
        /// 压力上限值
        /// </summary>
        public string UpperLimitTXT
        {
            get => _upperLimitTXT;
            set
            {
                _upperLimitTXT = value;
                RaisePropertyChanged(() => UpperLimitTXT);
            }
        }

        private string _lowerLimitTXT="-100";
        /// <summary>
        /// 压力下限值
        /// </summary>
        public string LowerLimitTXT
        {
            get => _lowerLimitTXT;
            set
            {
                _lowerLimitTXT = value;
                RaisePropertyChanged(() => LowerLimitTXT);
            }
        }

        private bool _isUpperLimitChecked;
        /// <summary>
        /// 获取或设置压力上限是否被选中。
        /// </summary>
        public bool IsUpperLimitChecked
        {
            get => _isUpperLimitChecked;
            set
            {
                _isUpperLimitChecked=value;
                ModifyLineSeriesVisibility("上限", value);
                RaisePropertyChanged(() => IsUpperLimitChecked);
            }
        }

        private bool _isLowerLimitChecked;
        /// <summary>
        /// 获取或设置压力下限是否被选中。
        /// </summary>
        public bool IsLowerLimitChecked
        {
            get => _isLowerLimitChecked;
            set
            {
                _isLowerLimitChecked=value;
                ModifyLineSeriesVisibility("下限", value);
                RaisePropertyChanged(() => IsLowerLimitChecked);
            }
        }


        private bool _isCan1Checked;
        /// <summary>
        /// 获取或设置罐1是否被选中。
        /// </summary>
        public bool IsCan1Checked
        {
            get => _isCan1Checked;
            set
            {
                _isCan1Checked = value;
                ModifyLineSeriesVisibility("罐1", value);
                RaisePropertyChanged(() => IsCan1Checked);
            }
        }
        private bool _isCan2Checked;
        /// <summary>
        /// 获取或设置罐2是否被选中。
        /// </summary>
        public bool IsCan2Checked
        {
            get => _isCan2Checked;
            set
            {
                _isCan2Checked=value;
                ModifyLineSeriesVisibility("罐2", value);
                RaisePropertyChanged(() => IsCan2Checked);
            }
        }
        private bool _isCan3Checked;
        /// <summary>
        /// 获取或设置罐3是否被选中。
        /// </summary>
        public bool IsCan3Checked
        {
            get => _isCan3Checked;
            set
            {
                _isCan3Checked=value;
                ModifyLineSeriesVisibility("罐3", value);
                RaisePropertyChanged(() => IsCan3Checked);
            }
        }
        private bool _isCan4Checked;

        /// <summary>
        /// 获取或设置罐4是否被选中。
        /// </summary>
        public bool IsCan4Checked
        {
            get => _isCan4Checked;
            set
            {
                _isCan4Checked=value;
                ModifyLineSeriesVisibility("罐4", value);
                RaisePropertyChanged(() => IsCan4Checked);
            }
        }
        private void ModifyLineSeriesVisibility(string targetName, bool isVisible)
        {

            // 使用 LINQ 查询找到具有指定名称的 LineSeries
            var lineToModify = Series.FirstOrDefault(series => series.Name == targetName);

            // 如果找到了要修改的线
            if (lineToModify != null)
            {
                // 将 IsVisible 属性修改为指定的值
                lineToModify.IsVisible = isVisible;
            }
        }
        private bool _isManualMode;
        /// <summary>
        /// 手自动模式切换
        /// </summary>
        public bool IsManualMode
        {
            get => _isManualMode;
            set
            {
                _isManualMode=value;
                CustomText = value ? "自动模式" : "手动模式";
                IsAuto = !value;
                SliderValueMax = value ? 300 : SliderValueMax;
                //StartDataCollectionThread(value);
                RaisePropertyChanged(() => IsManualMode);
            }
        }

        private string _customText;
        /// <summary>
        /// 手自动模式切换显示文本
        /// </summary>
        public string CustomText
        {
            get => _customText;
            set
            {
                _customText = value;
                RaisePropertyChanged(() => CustomText);
            }
        }
        private bool _isAuto;
        /// <summary>
        ///  是否手动模式
        /// </summary>
        public bool IsAuto
        {
            get => _isAuto;
            set
            {
                _isAuto = value;
                RaisePropertyChanged(() => IsAuto);
            }
        }




        public SolidColorPaint LegendTextPaint { get; set; } = new SolidColorPaint()
        {
            Color = SKColors.DarkSlateGray,
            SKTypeface = SKFontManager.Default.MatchCharacter('汉')
        };
        public SolidColorPaint TooltipTextPaint { get; set; } = new SolidColorPaint()
        {
            Color = SKColors.DarkSlateGray,
            SKTypeface = SKFontManager.Default.MatchCharacter('汉')
        };
        public Axis[] XAxes { get; set; }

        List<string> aXisLabels = new List<string>();
        //public Dictionary<DateTime, double> can1Data = new Dictionary<DateTime, double>();
        #endregion



        #region 方法
        /// <summary>
        /// 导出方法
        /// </summary>
        RelayCommand cmdExporToPressureChart;
        public RelayCommand CmdExporToPressureChart
        {
            get { return cmdExporToPressureChart ?? (cmdExporToPressureChart = new RelayCommand(() => DoCmdExporToPressureChart())); }
        }
        void DoCmdExporToPressureChart()
        {
            if(IsManualMode)
            {
                MessageBox.Show($"请在手动模式下操作导出");
                return;
            }
            if(pressureVesselData==null||pressureVesselData.Count<=0)
            {
                MessageBox.Show($"请先查询需要导出的数据");
                return;
            }

            // 获取用户选择的导出路径
            Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog();
            saveFileDialog.Filter = "Excel文件 (*.xlsx)|*.xlsx";
            if (saveFileDialog.ShowDialog() == true)
            {
                string filePath = saveFileDialog.FileName;

                var exportData = new List<PressureVesselModel>();

                if(IsCan1Checked)
                    exportData.AddRange(pressureVesselData.FindAll(x=>x.Type=="1"));
                if (IsCan2Checked)
                    exportData.AddRange(pressureVesselData.FindAll(x => x.Type == "2"));
                if (IsCan3Checked)
                    exportData.AddRange(pressureVesselData.FindAll(x => x.Type == "3"));
                if (IsCan4Checked)
                    exportData.AddRange(pressureVesselData.FindAll(x => x.Type == "4"));

                // 调用导出方法，将数据导出到Excel文件
                var re= ExcelHelper.Export(exportData, filePath);
                if (re)
                {
                    MessageBox.Show($"导出成功");
                }
                else
                {
                    MessageBox.Show($"导出失败！！！请联系管理员");
                }
                
            }
        }

        RelayCommand cmdImportFromExcel;
        public RelayCommand CmdImportFromExcel
        {
            get { return cmdImportFromExcel ?? (cmdImportFromExcel = new RelayCommand(() => DoCmdImportFromExcel())); }
        }
        void DoCmdImportFromExcel()
        {
            if (IsManualMode)
            {
                MessageBox.Show($"请在手动模式下操作");
                return;
            }

            // 创建文件选择对话框
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Excel文件 (*.xlsx)|*.xlsx";

            // 显示文件选择对话框
            if (openFileDialog.ShowDialog() == true)
            {
                string filePath = openFileDialog.FileName;

                try
                {
                    // 调用导入方法，传递文件路径
                    List<PressureVesselModel> importedData = ExcelHelper.Import(filePath);

                    if(importedData!=null&&importedData.Count>0)
                    {
                        pressureVesselData.Clear();
                        pressureVesselData.AddRange(importedData);
                        BuildManualCurve();
                    }
                    
                    MessageBox.Show($"导入成功");
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"导入失败: {ex.Message}");
                }
            }
        }

        /// <summary>
        /// 保存间隔存入数据库时间
        /// </summary>
        RelayCommand cmdIntervalInSecondsSave;
        public RelayCommand CmdIntervalInSecondsSave
        {
            get { return cmdIntervalInSecondsSave ?? (cmdIntervalInSecondsSave = new RelayCommand(() => DoCmdIntervalInSecondsSave())); }
        }
        void DoCmdIntervalInSecondsSave()
        {
            
        }

        /// <summary>
        /// 查询
        /// </summary>
        RelayCommand cmdQuery;
        public RelayCommand CmdQuery
        {
            get { return cmdQuery ?? (cmdQuery = new RelayCommand(() => DoCmdQuery())); }
        }
        void DoCmdQuery()
        {
            if (IsManualMode)
            {
                MessageBox.Show($"请在手动模式下操作查询");
                return;
            }
            pressureVesselData = _reporitory.GetPressureVesses(StartTime, EndTime);
            BuildManualCurve();
        }

        /// <summary>
        /// 批量插入
        /// </summary>
        RelayCommand cmdBulkInsert;
        public RelayCommand CmdBulkInsert
        {
            get { return cmdBulkInsert ?? (cmdBulkInsert = new RelayCommand(() => DoCmdBulkInsert())); }
        }
        void DoCmdBulkInsert()
        {
            if (IsManualMode)
            {
                MessageBox.Show($"请在手动模式下操作");
                return;
            }
            List<PressureVesselModel> pressureVesselList = new List<PressureVesselModel>();

            DateTime startTime = DateTime.Now;

            Random random = new Random();

            for (int i = 0; i < 300; i++)
            {
                // 生成随机的压力值（0到50之间的随机数）
                double pressureValue = random.NextDouble() * 50;

                // 创建PressureVesselModel对象并添加到列表中
                //pressureVesselList.Add(new PressureVesselModel
                //{
                //    TimeStamp = startTime.AddSeconds(i),
                //    Name = "罐1",
                //    Type = "1",
                //    PressureValue = pressureValue
                //});

                pressureValue = random.NextDouble() * 50;

                // 创建PressureVesselModel对象并添加到列表中
                pressureVesselList.Add(new PressureVesselModel
                {
                    TimeStamp = startTime.AddSeconds(i),
                    Name = "罐2",
                    Type = "2",
                    PressureValue = pressureValue
                });

                pressureValue = random.NextDouble() * 50;

                // 创建PressureVesselModel对象并添加到列表中
                pressureVesselList.Add(new PressureVesselModel
                {
                    TimeStamp = startTime.AddSeconds(i),
                    Name = "罐3",
                    Type = "3",
                    PressureValue = pressureValue
                });


                pressureValue = random.NextDouble() * 50;

                // 创建PressureVesselModel对象并添加到列表中
                pressureVesselList.Add(new PressureVesselModel
                {
                    TimeStamp = startTime.AddSeconds(i),
                    Name = "罐4",
                    Type = "4",
                    PressureValue = pressureValue
                });
            }
            bool re= _reporitory.BulkInsertPressureVessels(pressureVesselList);
            if(re)
            {
                MessageBox.Show($"插入成功");
            }
            else
            {
                MessageBox.Show($"插入失败！！！");
            }
        }


        //线条颜色

        SKColor _upperLimitcolor = new SKColor(220, 20, 60, 255);
        SKColor _lowerLimitcolor = new SKColor(255, 165, 0, 255);
        SKColor _can1color = new SKColor(0, 255, 0, 255);
        SKColor _can2color = new SKColor(0, 255, 255, 255);
        SKColor _can3color = new SKColor(30, 144, 255, 255);
        SKColor _can4color = new SKColor(238, 130, 238, 255);

        PressureVesselReporitory _reporitory=new PressureVesselReporitory();
        public void Init()
        {
            try
            {
                XxisInit();

                //上限条
                var _upperLimit = new LineSeries<double>
                {
                    Values = UpperLimit, // 设置 LineSeries 的数据源为 UpperLimit 集合
                    Stroke = new LiveChartsCore.SkiaSharpView.Painting.SolidColorPaint(_upperLimitcolor, LineSize), // 设置线条颜色
                    GeometryStroke = new LiveChartsCore.SkiaSharpView.Painting.SolidColorPaint(_upperLimitcolor, LineSize), // 设置线条的几何颜色
                    LineSmoothness = LineSmoothness, // 禁用线条平滑效果
                    GeometrySize = GeometrySize, // 设置几何尺寸
                    Fill = null, // 禁用填充效果
                    Name = "上限", // 设置线的名称为 "上限"
                    //IsVisible = IsUpperLimitChecked
                };
                //下限条
                var _lowerLimit = new LineSeries<double>
                {
                    Values = LowerLimit,
                    Stroke = new LiveChartsCore.SkiaSharpView.Painting.SolidColorPaint(_lowerLimitcolor, LineSize),
                    GeometryStroke = new LiveChartsCore.SkiaSharpView.Painting.SolidColorPaint(_lowerLimitcolor, LineSize),
                    LineSmoothness = LineSmoothness,
                    GeometrySize = GeometrySize,
                    Fill = null,
                    Name = "下限",
                    IsVisible = IsLowerLimitChecked
                };
                //下限条
                ////罐1
                var _can1 = new LineSeries<double>
                {
                    Values = Can1,
                    Stroke = new LiveChartsCore.SkiaSharpView.Painting.SolidColorPaint(_can1color, LineSize),
                    GeometryStroke = new LiveChartsCore.SkiaSharpView.Painting.SolidColorPaint(_can1color, LineSize),
                    LineSmoothness = LineSmoothness,
                    GeometrySize = GeometrySize,
                    //Fill = new SolidColorPaint(color),
                    Fill = null,
                    Name = "罐1",
                    IsVisible = IsCan1Checked,
                };

                //罐2
                var _can2 = new LineSeries<double>
                {
                    Values = Can2,
                    Stroke = new LiveChartsCore.SkiaSharpView.Painting.SolidColorPaint(_can2color, LineSize),
                    GeometryStroke = new LiveChartsCore.SkiaSharpView.Painting.SolidColorPaint(_can2color, LineSize),
                    LineSmoothness = LineSmoothness,
                    GeometrySize = GeometrySize,
                    Fill = null,
                    Name = "罐2",
                    IsVisible = IsCan2Checked,
                };
                //罐3
                var _can3 = new LineSeries<double>
                {
                    Values = Can3,
                    Stroke = new LiveChartsCore.SkiaSharpView.Painting.SolidColorPaint(_can3color, LineSize),
                    GeometryStroke = new LiveChartsCore.SkiaSharpView.Painting.SolidColorPaint(_can3color, LineSize),
                    LineSmoothness = LineSmoothness,
                    GeometrySize = GeometrySize,
                    Fill = null,
                    Name = "罐3",
                    IsVisible = IsCan3Checked,
                };
                //罐4
                var _can4 = new LineSeries<double>
                {
                    Values = Can4,
                    Stroke = new LiveChartsCore.SkiaSharpView.Painting.SolidColorPaint(_can4color, LineSize),
                    GeometryStroke = new LiveChartsCore.SkiaSharpView.Painting.SolidColorPaint(_can4color, LineSize),
                    LineSmoothness = LineSmoothness,
                    GeometrySize = GeometrySize,
                    Fill = null,
                    Name = "罐4",
                    IsVisible = IsCan4Checked
                };

                Series.Add(_upperLimit);
                Series.Add(_lowerLimit);
                Series.Add(_can1);
                Series.Add(_can2);
                Series.Add(_can3);
                Series.Add(_can4);
                //for (int i = 0; i < 10; i++)
                //{
                //    var aa = _random.Next(0, 50);
                //    Can1.Add(aa);
                //    var bb = _random.Next(0, 50);
                //    Can2.Add(bb);
                //    var cc = _random.Next(0, 50);
                //    Can3.Add(cc);
                //    var dd = _random.Next(0, 50);
                //    Can4.Add(dd);
                //}



            }
            catch (Exception ex)
            {
                MessageBox.Show($"压力曲线图初始化失败{ex.ToString()}");
            }
        }
        /// <summary>
        /// 平滑度
        /// </summary>
        private void SetGeometrySeries()
        {
            foreach (var series in Series)
            {
                if (series is LineSeries<double> lineSeries)
                {
                    lineSeries.LineSmoothness = LineSmoothness;
                    lineSeries.GeometrySize = GeometrySize;
                }
            }
        }

        /// <summary>
        /// 调整线条大小
        /// </summary>
        /// <param name="value"></param>
        private void SetLineSizeSeries(int value)
        {
            foreach (var series in Series)
            {
                if (series is LineSeries<double> lineSeries)
                {
                    lineSeries.Stroke.StrokeThickness = value;
                }
            }
        }
        /// <summary>
        /// 填充背景
        /// </summary>
        /// <param name="value"></param>
        private void SetFillForLineSeries(bool value)
        {
            SolidColorPaint _fill;

            foreach (var series in Series)
            {
                if (series is LineSeries<double> lineSeries)
                {
                    switch (series.Name)
                    {
                        case "罐1":
                            _fill = new SolidColorPaint(_can1color.WithAlpha((byte)OpacityFill));
                            break;
                        case "罐2":
                            _fill = new SolidColorPaint(_can2color.WithAlpha((byte)OpacityFill));
                            break;
                        case "罐3":
                            _fill = new SolidColorPaint(_can3color.WithAlpha((byte)OpacityFill));
                            break;
                        case "罐4":
                            _fill = new SolidColorPaint(_can4color.WithAlpha((byte)OpacityFill));
                            break;
                        default:
                            _fill = null;
                            break;
                    }
                    lineSeries.Fill = value ? _fill : null;
                }
            }
        }
        private void XxisInit()
        {
            if(xAxis==null)
            {
                xAxis = new Axis
                {
                    Labels = aXisLabels,
                    MaxLimit = SliderValue,
                    MinLimit = 0
                };

                xAxis.PropertyChanged += (object sender, System.ComponentModel.PropertyChangedEventArgs e) =>
                {
                    if (e.PropertyName != nameof(xAxis.MaxLimit) && e.PropertyName != nameof(xAxis.MinLimit))
                    {
                        // 在这里，只有当 MaxLimit 或 MinLimit 更改时才会执行代码
                        // 表示用户正在进行缩放操作
                        var minXVisible = xAxis.MinLimit;
                        var maxXVisible = xAxis.MaxLimit;
                    }
                };

                XAxes = new Axis[]
                 {
                       xAxis
                  };

             
            }
            else
            {
                //xAxis.MaxLimit = SliderValue;
                xAxis.MaxLimit = aXisLabels.Count;
                xAxis.MinLimit = aXisLabels.Count > SliderValue ? aXisLabels.Count - SliderValue : aXisLabels.Count - 10;
            }

        }

        private CancellationTokenSource _taskTokenSource;
        private Task _dataCollectionTask;

        private void StartDataCollectionThread(bool start)
        {
            if (start)
            {
                if (_taskTokenSource != null && !_taskTokenSource.Token.IsCancellationRequested)
                {
                    // 如果任务正在运行，取消它
                    _taskTokenSource.Cancel();
                    _dataCollectionTask.Wait(); // 等待任务完成
                }

                // 创建一个新的 CancellationTokenSource
                _taskTokenSource = new CancellationTokenSource();

                // 创建并启动一个新的任务
                _dataCollectionTask = Task.Run(() =>
                {
                    while (!_taskTokenSource.Token.IsCancellationRequested)
                    {
                        // 重新开始线程的逻辑

                        DateTime dateData = DateTime.Now;
                        double value = 1.0;

                        Can1.Add(_random.Next(0, 50));

                        Can2.Add(_random.Next(0, 50));

                        Can3.Add(_random.Next(0, 50));

                        Can4.Add(_random.Next(0, 50));

                        UpperLimit.Add(double.Parse(UpperLimitTXT));

                        LowerLimit.Add(double.Parse(LowerLimitTXT));

                        aXisLabels.Add(dateData.ToString());

                        if(IsJump)
                        {
                            xAxis.MaxLimit = aXisLabels.Count;
                            xAxis.MinLimit = aXisLabels.Count > SliderValue ? aXisLabels.Count - SliderValue : aXisLabels.Count - 10;
                        }
                      

                        Thread.Sleep(1000);
                    }
                }, _taskTokenSource.Token);
            }
            else
            {
                // 取消任务
                if (_taskTokenSource != null)
                {
                    _taskTokenSource.Cancel();
                    _dataCollectionTask.Wait(); // 等待任务完成
                }
                pressureVesselData.Clear();
            }
        }

        private List<PressureVesselModel> pressureValueCache = new List<PressureVesselModel>();
        public void AddPressureChart(List<PressureVesselModel> value)
        {
            if (IsManualMode)
            {
                DateTime dateData = DateTime.Now;

                //如果大于最大值的两倍则清掉最后的一部分
                if(aXisLabels.Count>SliderValueMax*2)
                {
                    Task.Run(() =>
                    {
                        aXisLabels.RemoveRange(0, SliderValueMax);

                        for (int i = 0; i < SliderValueMax; i++)
                        {
                            Can1.RemoveAt(0);
                            Can2.RemoveAt(0);
                            Can3.RemoveAt(0);
                            Can4.RemoveAt(0);
                            UpperLimit.RemoveAt(0);
                            LowerLimit.RemoveAt(0);
                        }
                    });
                }

                value.ForEach(x =>
                {
                    switch(x.Type) 
                    {
                        case "1":
                            Can1.Add(x.PressureValue);
                            break;
                        case "2":
                            Can2.Add(x.PressureValue);
                            break;
                        case "3":
                            Can3.Add(x.PressureValue);
                            break;
                        case "4":
                            Can4.Add(x.PressureValue);
                            break;
                    }
                });
                //Can1.Add(pressureValue);

                //Can2.Add(pressureValue);

                //Can3.Add(pressureValue);

                //Can4.Add(pressureValue);

                UpperLimit.Add(double.Parse(UpperLimitTXT));

                LowerLimit.Add(double.Parse(LowerLimitTXT));

                aXisLabels.Add(dateData.ToString());
                if (IsJump)
                {
                    xAxis.MaxLimit = aXisLabels.Count;
                    xAxis.MinLimit = aXisLabels.Count > SliderValue ? aXisLabels.Count - SliderValue : aXisLabels.Count - 10;
                }
            }
            // 存储压力值到缓存中
            pressureValueCache.AddRange(value);
            // 检测压力值数量是否大于等于设定的时间
            if (pressureValueCache.Count >= (IntervalInSeconds*4))
            {
                BulkInsertPressureValues(); //插入数据库
                pressureValueCache.Clear(); // 清空缓存
            }
        }

        public bool BulkInsertPressureValues()
        {
            try
            {
                if(pressureValueCache!=null&& pressureValueCache.Count>0)
                {
                    bool re = _reporitory.BulkInsertPressureVessels(pressureValueCache);
                    return re;
                }
                return false;
            }
            catch (Exception ex)
            {
                // 处理异常
                // 返回 false 或抛出异常，具体根据业务逻辑决定
                return false;
            }
        }



        /// <summary>
        /// 手动根据查询的数据构建曲线图
        /// </summary>
        /// <param name="curveDataPoints"></param>
        public void BuildManualCurve()
        {
            try
            {
                aXisLabels.Clear();
                Can1.Clear();
                Can2.Clear();
                Can3.Clear();
                Can4.Clear();
                UpperLimit.Clear();
                LowerLimit.Clear();


                // 使用字典来追踪每个 Type 的数据项数量
                Dictionary<string, int> typeCount = new Dictionary<string, int>();

                // 循环处理数据
                foreach (var item in pressureVesselData)
                {
                    if (item.Type == "1")
                    {
                        Can1.Add(item.PressureValue);
                    }
                    else if (item.Type == "2")
                    {
                        Can2.Add(item.PressureValue);
                    }
                    else if (item.Type == "3")
                    {
                        Can3.Add(item.PressureValue);
                      
                    }
                    else if (item.Type == "4")
                    {
                        Can4.Add(item.PressureValue);
                    }

                    // 更新 Type 的计数
                    if (typeCount.ContainsKey(item.Type))
                    {
                        typeCount[item.Type]++;
                    }
                    else
                    {
                        typeCount[item.Type] = 1;
                    }
                }

                string firstType = typeCount.Keys.FirstOrDefault();

                pressureVesselData.FindAll(x => x.Type == firstType).ForEach(item =>
                {
                    // 添加共享的数据
                    aXisLabels.Add(item.TimeStamp.ToString());
                    UpperLimit.Add(double.Parse(UpperLimitTXT));
                    LowerLimit.Add(double.Parse(LowerLimitTXT));
                });
             
                SliderValueMax = pressureVesselData.Count/ typeCount.Count;
                //XxisInit();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询失败：{ex.ToString()}");
            }
          
            //Parallel.ForEach(pressureVesselData, item =>
            //{
            //    aXisLabels.Add(item.TimeStamp.ToString());
            //    Can1.Add(item.PressureValue);
            //});

        }
        #endregion

        public List<PressureVesselModel> pressureVesselData=new List<PressureVesselModel>();
    }

  
}

